<template>
  <div class="all">
    <div class="button">
        <el-button @click="addBtn($event)">添加</el-button>
        <el-button @click="putBtn($event)">修改</el-button>
        <el-button @click="delBtn($event)">删除</el-button>
      </div>
      <el-table
        
        :data="tableData"
        :row-style="{height: '60px'}"
        stripe
        style="width: 100%"
       
        @selection-change="handleSelectionChange"
      >

        <el-table-column
          type="selection"
          width="55px"
          fixed="left"
        />

        <el-table-column
          label="序号"
          type="index"
        >
          <template scope="scope">
            <span>{{ (currentPage - 1) * pageSize + scope.$index + 1 }}</span>
          </template>
        </el-table-column>

        <el-table-column
          v-for="(item,index) in title"
          :key="index"
          :prop="item.prop"
          :label="item.label"
          show-overflow-tooltip
        >

        </el-table-column>

        <el-table-column
          align="center"
          label="上架"
          show-overflow-tooltip
        >
          <template #default="{ row }">
            <el-switch
              v-model.number="row.shelf"
              active-color="#1890FF"
              inactive-color="#A9A8A8"
              :active-value="1"
              :inactive-value="0"
              @change="shelfchange(row)"
            />
          </template>
        </el-table-column>

        <el-table-column
          fixed="right"
          label="图片"
          width="100"
        >
          <template slot-scope="scope">
            <el-button
              type="text"
              size="small"
              @click="viewImg(scope.row)"
            >查看</el-button>
          </template>
        </el-table-column>

      </el-table>
      <div class="page"> 
        <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="currentPage"
        :page-sizes="[10, 20, 50, 100, 200]"
        :page-size="pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
        </el-pagination>
    </div>

    <!-- 查看 -->
  <div class="showImg">
    <el-dialog
      title="房间图片"
      :visible.sync="dialogVisibleImg"
      width="450px"
      center="center"
      :before-close="viewClose"
    >
      <!-- 弹窗内容 -->
      <div
        class="showcontent"
        style="height:300px; width: 430px;"
      >
        <img
          id="imgShow"
          :src="imgPath"
          alt
          style="height:300px; width: 400px;"
        >
      </div>

    </el-dialog>
  </div>


      <!-- 新增修改 -->
      <div class="dialog">
    <el-dialog
      :title="dialogTitle"
      :visible.sync="dialogVisible"
      width="27.683%"
      center="center"
      :before-close="handleClose"
    >
      <!-- 弹窗内容 -->
      <div class="content">
        <el-form
          ref="submitData"
          :model="submitData"
          
          label-width="100px"
          class="demo-ruleForm"
        >

          <!-- 名字 -->
          <el-form-item
            label="名字:"
            prop="name"
          >
            <el-input
              v-model="submitData.name"
              placeholder="输入名字"
            />
          </el-form-item>

          <!-- 类型 -->
          <el-form-item
            label="类型:"
            prop="type_id"
          >
            <el-select
              v-model="submitData.type_id"
              clearable
              placeholder="请选择"
            >
              <el-option
                v-for="(item,index) in goodsTypeList"
                :key="index"
                :label="item.name"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <!-- 排序 -->
          <el-form-item
            label="排序:"
            prop="sort"
          >
            <el-input
              v-model="submitData.sort"
              placeholder="排序"
            />
          </el-form-item>

          <!-- 描述 -->
          <el-form-item
            label="描述:"
            prop="describe"
          >
            <el-input
              v-model="submitData.describe"
              placeholder="描述"
            />
          </el-form-item>

          <!-- 价格 -->
          <el-form-item
            label="价格:"
            prop="price"
          >
            <el-input
              v-model="submitData.price"
              placeholder="价格"
            />
          </el-form-item>

         

          <!-- 添加图片 -->
          <el-form-item
            label="添加图片:"
            prop="file"
          >
            <div class="imgBtn">
              <span class="img_btn"><i v-show="!addImgShow">+</i>
                <input
                ref="inputFile"
                  id=""
                  type="file"
                  name=""
                  @change="selImg($event)"
                >
                <img
                  v-show="addImgShow"
                  ref="fil_img"
                  :src="imgPath"
                  alt=""
                  @click="selImg($event)"
                >
              </span>

            </div>
          </el-form-item>

        </el-form>
      </div>

      <span
        slot="footer"
        class="dialog-footer"
      >
        <div class="footer_button">
          <el-button
            type="primary"
            @click="submitForm('submitData')"
          >提交</el-button>
        </div>
      </span>
    </el-dialog>
  </div>
  </div>
</template>

<script>
import {getGoods,getGoodsType} from "@/api/dataReq"
import { req } from '@/api/basicReq'
export default {
  name: 'Devices',
  props: {
  
  },
  data(){
      return{
          title:[
          { prop: 'name', label: '名字' },
          { prop: 'type_name', label: '类型' },
          { prop: 'sort', label: '排序' },
          { prop: 'describe', label: '描述' },
          { prop: 'price', label: '价格' },
          { prop: 'createtime', label: '创建时间' },
          { prop: 'updatetime', label: '更新时间' },
          
          ],
          tableData: [],
          selectData: {},
          currentPage: 1, 
          pageSize: 10, 
          total: 100, 
          dialogVisibleImg:false,
          imgPath: "",
          dialogVisible:false,
          dialogTitle: "新增",
          submitData:{},
          goodsTypeList: [],
          addImgShow:false,
          result:null,
          Method:"post",
      }
  },
  created(){
    this.getData()
    this.getTypeList()
  },

  methods:{
    getData(){
      var reqData  ={
        page_size: this.pageSize,
        page_num: this.currentPage,
      }
      getGoods(reqData).then(response => {
        if (response.code == '1') {
          // console.log(response)
         this.tableData = response.data
         this.total = response.total

        } else {
          
        }
      }).catch(error => {
        console.log('err', error)
        
      })
    },
    getTypeList(){
      var reqData  ={all:1}
      getGoodsType(reqData).then(response => {
        if (response.code == '1') {
          // console.log(response)
         this.goodsTypeList = response.data

        } else {
          
        }
      }).catch(error => {
        console.log('err', error)
        
      })

    },

    shelfchange(row) {
      console.log(row)

      // var par = row
      var formData = new FormData()
      for (const key in row) {
          if (row[key] !== null) {
            formData.append(key, row[key])
        }
          }
      var data = {
        url: 'goods/GoodList',
        method: 'put',
        data: formData
      }
      req(data)
        .then((res) => {
          if (res.code == '1') {
            // console.log(res)
            // console.log(formData)
            this.getData()
            //   this.dialogVisible = false
          }
        })
        .catch()
    },

    handleClose(){
      this.dialogVisible = false
    },

      handleClick(row){

      },
      handleSelectionChange(val) {
      this.selectData = val
    
  },
  handleSizeChange(val) {
      // console.log(`每页 ${val} 条`);
      this.pageSize = val
      this.getData()
    },
    handleCurrentChange(val) {
      // console.log(`当前页: ${val}`);
      this.currentPage = val
      this.getData()
    },
  addBtn(ev){
    this.dialogVisible = true

    this.dialogTitle = '添加'
    if (this.submitData) {
      this.submitData = {}
    }
    this.imgPath = ''
    this.addImgShow = false
    this.dialogVisible = true
    this.Method = 'post'
  },

  putBtn(ev){
    this.Method = 'put'
    this.dialogTitle = '修改'
    if (this.selectData.length == '1') {
      this.submitData = { ...this.selectData[0] }
      this.dialogVisible = true
      this.imgPath = cfg.img_url + this.submitData.img + '?' + Date.now()
      this.addImgShow = true
    } else if (this.selectData.length >= '1') {
      this.$message({
        message: '只能选择一条要修改的数据',
        type: 'warning'
      })
    } else {
      this.$message({
        message: '请先选择要修改的数据',
        type: 'warning'
      })
    }
  },
  delBtn(ev){
    if (this.selectData.length > 0) {
      const idList = []
      this.selectData.forEach((item) => {
        idList.push(item.id)
      })
      var data = {
        url: 'goods/GoodList',
        method: 'delete',
        data: { id: idList }
      }
      req(data).then((res) => {
       
        if (res.code == 1) {
          this.$message.success('删除成功')
          if (
            idList.length == this.tableData.length &&
            this.currentPage != 1
          ) {
            this.currentPage--
          }
          this.getData()
        }
      })
    } else {
      this.$message({
        message: '请先选择要删除的数据',
        type: 'warning'
      })
    }
  },

  // 查看图片
  viewImg(val) {
    this.dialogVisibleImg = true
    this.imgPath = cfg.img_url + val.img + '?' + Date.now()
    // console.log(this.imgPath)
  },
  // 关闭查看
  viewClose(){
    // this.dialogVisible = false
    this.dialogVisibleImg = false
  },

  // 点击图像
  selImg(e) {
    // console.log(e.target.files[0]);//获取图片数据
    // 保存数据
    const this_ = this
    // this.imgPath = e.target.files[0]
    this.submitData.img = e.target.files[0]

    // console.log(this.imgPath)
    const file = new FileReader() // 创建一个图片读取对象
    file.readAsDataURL(e.target.files[0]) // 读取
    file.onload = function() {
      // console.log(this.result) // 获取64的图片码
      if (e.target.files[0]) {
        this_.addImgShow = true
        this_.$refs.fil_img.setAttribute('src', this.result)
        // console.log(this_.$refs.fil_img)
        this_.$refs.inputFile.value=null;
      }
    }
  },
  submitForm(){
    // console.log(this.submitData)
    var formData = new FormData()
    for (const key in this.submitData) {
        if (this.submitData[key] !== null) {
          formData.append(key, this.submitData[key])
      }
        }
    
    var reqData = {
      url: 'goods/GoodList',
      method: this.Method,
      data: formData
    }
    req(reqData).then(response => {
        if (response.code == '1') {
          if(this.Method=="post"){
            this.$message.success('新增成功')
          }else{
            this.$message.success('修改成功')
          }
          
          this.dialogVisible = false
          this.addImgShow = false
          this.getData()
        } else {
          
        }
      }).catch(error => {
        console.log('err', error)
        
      })
    // console.log(formData)
  },

  }
  
}
</script>
  <style lang="scss" scoped>
  @import '~@/style/minxin.scss';
.content{
    width: 100%;
    display: flex;
    flex-direction: row-reverse;
    justify-content: space-between;
    .button {
      display: flex;
      justify-content: flex-start;
    }
  }
  .page{
    display: flex;
justify-content: center;
align-items: center;
margin-top: 20px;
  }

  .imgBtn {
    // width: 100%;
    position: relative;
    .img_btn {
      @include flex-center;
      border: 1px solid #dcdfe6;
      border-radius: 5px;
      color: #dcdfe6;
      font-size: 30px;
      width: 80px;
      height: 80px;
      overflow: hidden;
    }

    .img_btn > input {
      position: absolute;
      top: 0;
      left: 0;
      width: 80px;
      height: 80px;
      z-index: 1000;
      opacity: 0;
      cursor: pointer;
    }

    .img_btn > img {
      width: 75px;
      height: 75px;
      object-fit: scale-down;
      position: absolute;
      top: center;
      left: center;
    }
  }
  </style>
  